package cn.wolfcode.realm;

import cn.wolfcode.domain.Student;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.mapper.StudentMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class StudentRealm extends AuthorizingRealm {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private StudentMapper studentMapper;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Student student = (Student) principalCollection.getPrimaryPrincipal();
        if (student.isAdmin()) {
            info.addStringPermission("*:*");
        } else {
            List<String> permissionList = permissionMapper.selectPermissionsByStudentId(student.getId());
            info.addStringPermissions(permissionList);
        }
        return info;

    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        Student student = studentMapper.selByUsername(username);
        if (student == null) {
            return null;
        } else {
            return new SimpleAuthenticationInfo(student, student.getPassword(),
                    ByteSource.Util.bytes(student.getSalt()), getName());
        }

    }
}
